# 数据记录器

import csv
import time
from datetime import datetime


class DataLogger:
    def __init__(self):
        self.log_file = None
        self.csv_writer = None

    def start_logging(self, filename):
        """开始记录数据"""
        try:
            self.log_file = open(filename, 'w', newline='')
            self.csv_writer = csv.writer(self.log_file)
            # 写入表头
            self.csv_writer.writerow(['Timestamp', 'DateTime', 'Temperature', 'Pressure', 'Flow'])
        except Exception as e:
            raise Exception(f"无法创建日志文件: {str(e)}")

    def stop_logging(self):
        """停止记录数据"""
        if self.log_file:
            self.log_file.close()
        self.log_file = None
        self.csv_writer = None

    def log_data(self, data):
        """记录数据"""
        if not self.csv_writer:
            return

        timestamp = time.time()
        dt = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

        temperature = data.get('temperature', '')
        pressure = data.get('pressure', '')
        flow = data.get('flow', '')

        self.csv_writer.writerow([timestamp, dt, temperature, pressure, flow])
        self.log_file.flush()  # 确保数据立即写入文件